package com.xinnet.mms.customtransfer.service.impl;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.customerManage.dao.CustomerManageDao;
import com.xinnet.mms.customerManage.service.CustomerManageService;
import com.xinnet.mms.customerstate.service.CustomerStateHistService;
import com.xinnet.mms.customtransfer.service.DealNewRegisterCustomerService;
import com.xinnet.mms.empcustomrelation.service.EmpCustomRelationService;
import com.xinnet.mms.entity.CustomStateHist;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.utils.CustomerManage;
import com.xinnet.mms.utils.DateUtil;

@Service("dealNewRegisterCustomerService")
public class DealNewRegisterCustomerServiceImpl implements DealNewRegisterCustomerService{

	@Autowired
	private EmpCustomRelationService empCustomRelationService;
	@Autowired
	private CustomerStateHistService customerStateHistService;
	@Autowired
	private CustomerManageService customerManageService;
	@Autowired
	private CustomerManageDao customerManageDao;
	@Autowired
	private CustomAllotService customAllotService;
	
	private static Logger log=LoggerFactory.getLogger(DealNewRegisterCustomerServiceImpl.class);
	
	/**
	 * 分页获流转数据
	 */
	@Override
	public void dealwithNewCustomer() {
		//
		this.checkNormalorTest();
        log.info("************************************************************************************新注册客户流转开始********************************************"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //分页获取新注册客户信息
        Customer customer = new Customer();
        customer.setCustomType(CustomerManage.NEW_CUSTOMER);
        int count = empCustomRelationService.getTransferCustomCount(customer);
        
        PageView<Customer> page = new PageView<Customer>();
        page.setPageSize(2000); //每页显示2q条
        page.setRowCount(count);
        long pageCount = page.getPageCount();
        
        for(int i = 1;i<=pageCount;i++){
        	page.setPageNow(i);
        	Integer startPage = page.getFirstResult();
    		customer.setLimitTop(startPage);
    		customer.setLimitDown(page.getPageSize());
        	
        	List<EmpCustomRelation> newRegisterCustomList = empCustomRelationService.getTransferCustom(customer);
        	for (Iterator<EmpCustomRelation> iterator = newRegisterCustomList.iterator(); iterator.hasNext();) {
    			EmpCustomRelation newRegisterCustom = (EmpCustomRelation) iterator.next();
    			this.doSingleCustomer(newRegisterCustom);
    		}
        }
		log.info("************************************************************************************新注册客户流转结束********************************************"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	}
	
	/**
	 * 处理每个客户的流转
	 * @param newRegisterCustom
	 */
	private void doSingleCustomer(EmpCustomRelation newRegisterCustom) {
		try {
		//新注册除了手动流向意向客户，其余超过截止期限，流入保护期
		String customerId = newRegisterCustom.getCustomId();
		//要处理的客户
		Customer customer = new Customer();
		//判定截止日期的标志位
		boolean flag = false;
		
		customer = customAllotService.getCustomerById(customerId);
		
		//新需求中，新注册客户的停留时间是5天。先判定是否到达截止日期
		flag = this.checkHoldTime(customer);
		//true时，到期，开始变更状态
		if(flag){
			//变更custom表状态
			customer.setCustomerType(CustomerManage.PROTCET_CUSTOMER);
			//由于dao层方法混乱，重构又可能带来意料之外的情况，故在此使用dao层方法
			customerManageDao.updateCustomType(customer);
			newRegisterCustom.setCustomType(CustomerManage.PROTCET_CUSTOMER);
			empCustomRelationService.updateEmpCustomRelation(newRegisterCustom);
			//添加客户状态变更记录
			CustomStateHist customStateHist=new CustomStateHist();
			customStateHist.setId(UUID.randomUUID().toString());
			customStateHist.setProductId("");
			customStateHist.setCustomId(customer.getCusId());
			customStateHist.setCustomType(CustomerManage.PROTCET_CUSTOMER);
			customStateHist.setCustomState(CustomerManage.ACCEPT_YES);
			customStateHist.setEmpId(customer.getEmpId());
			customStateHist.setPusherId("");
			customStateHist.setIsReceive(CustomerManage.ACCEPT_YES);
			customStateHist.setPushHistId("");
			customStateHist.setPushDesc("");
			customStateHist.setProductCode(customer.getProductCode());
			customerStateHistService.addCustomerStateHist(customStateHist);
		}
		
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 是否中断流转执行
	 */
	public void checkNormalorTest(){
		//配置文件中默认设置为false，这里没起到控制作用，为了方便测试其他非流程功能，保留以下代码
		String isTest = ConfigUtil.getString("isTest");
        if(isTest==null || "".equals(isTest)){
        	log.error("配置异常：是否是测试环境");
        	return;
        }		
	}
	
	/**
	 * 判断是否超过保留期限    暂定5天保留期，后期调整为变量
	 * 
	 * @param customer
	 * @return true 超过  | false 没有超过
	 */
	public boolean checkHoldTime(Customer customer){
		//当前时间
		Date now = DateUtil.getSysDate();
		//注册时间
		String addtimeString = customer.getAddTime();
		Date addtimeDate = DateUtil.parseDateTime(addtimeString);
		//截止时间   ： 注册时间+保留期限
		Date holdDate = DateUtil.addDate(addtimeDate, 5);
		
		if(now.after(holdDate)){
			return true;
		}else{
			return false;
		}
		
	}
	

}
